/**
 * 注册校验
 * @authors gaocc 
 * @date    2014-10-09 11:10:42
 * @update  2014-10-09 11:10:42
 * @for new_register.jsp
 * @version $Id$
 */
$(function() {
    BSTYUN.register.init();
});

/**
 * 手机方式注册
 */
function registerByPhone(){
	BSTYUN.register.clearErrorMsg($("#phone"));
	BSTYUN.register.clearErrorMsg($("#vftn_code"));
	BSTYUN.register.clearErrorMsg($("#psd"));
	BSTYUN.register.clearErrorMsg($("#cfm_psd"));
	BSTYUN.register.clearErrorMsg($("#realName"));
	$("#prompt").show();
	$("#go2register").val("同意协议并注册");
	$("#email").val("");
	$(".phone").show();
	$(".email").hide();
}

/**
 * 邮箱方式注册
 */
function registerByEmail(){
	$("#email").next('.error_msg').remove()
	$("#prompt").hide();
	$("#go2register").val("立即绑定邮箱");
//	$("#email").val("");
	$("#phone").val("");
	$("#vftn_code").val("");
	$("#psd").val("");
	$("#cfm_psd").val("");
	$("#realName").val("");
	$(".phone").hide();
	$(".email").show();
}
var BSTYUN = BSTYUN || {};

BSTYUN.check = {
    //IE6判定
    isIE6: window.VBArray && !window.XMLHttpRequest,
    //判断是否为中英文，数字，下划线，减号
    isNick: function(str) {
        var nickReg = /^[\u4e00-\u9fa5A-Za-z0-9-_]+$/;
        return nickReg.test(str);
    },
    //判断邮箱
    isEmail: function(str) {
        var emailReg = /^[a-z0-9][\w\.]*@([a-z0-9][a-z0-9-]*\.)+[a-z]{2,5}$/i;
        return emailReg.test(str);
    },
    //判断手机.
    isMobile: function(str) {
        var mobileReg = /^1[345678][0-9]{9}$/;
        return mobileReg.test(str);
    },
    // 判断固话
    isTelephone: function(str) {
        var phoneReg = /^0\d{2,3}-\d{5,9}$/;
        return phoneReg.test(str);
    },
    //判断URL
    isUrl: function(str) {
        var urlReg = /^http:\/\/([\w-]+\.)+[\w-]+(\/[\w-.\/?%&=]*)?$/;
        return urlReg.test(str);
    },
    //判断数字
    isNum: function(str) {
        var numReg = /^[0-9]\d*$/;
        return numReg.test(str);
    }
};
BSTYUN.register = {
    $inputs: null,
    flag: { realName: false, email: false, psd: false, cfm_psd: false, phone: false, vftn_code: false, picode: false},
    _timer: null,/*全局定时器*/
    init:function() {
        var that = this;
        /*获取input元素*/
        that.$inputs = $('.input_box').find('input');
        /*检测信息*/
        that.checkInfor();
        /*发送短信验证码*/
        that.sendSmsCode();
        /*提交注册*/
        that.submitRegister();
        /*图片验证码替换*/
        that.changePicCode();
        /*初始化注册方式页面*/
        that.registerByWay();
        
        
    },
    checkInfor:function() {
        var that = this;
        /*获取焦点，清空错误信息*/
        that.$inputs.on('focus', function(event) {
            that.clearErrorMsg($(this));
            /*失去焦点，检测信息正确性*/
        }).on('blur', function(event) {
            var $this = $(this),
                typename = $this.attr('name'),
                val = $.trim($this.val());
            /*输入内容为空，则提示不能为空*/
            if(val == '' || val.length == 0){
                that.addErrorMsg($this,'不能为空');
                return false;
            }
            if (typename == 'phone') {
            	var $send = $('#getvftn_code');
                if (!BSTYUN.check.isMobile(val)) {
                    that.addErrorMsg($this,'手机格式不正确');
                }else{
                	$.ajax({
                        type: "post",
                        url: "/user/tel?random="+Math.random(),
                        data: {userTel:val},
                        async:false,
                        success: function(data){
                          if(data==false){
                              that.addErrorMsg($this,"该手机已被注册");
                              $send.addClass("disabled");
                          }else{
                        	  that.clearErrorMsg($this);
                        	  $send.removeClass("disabled");
                          }
                       }
                    });
                }
            }else if(typename =='email'){
				if (!BSTYUN.check.isEmail(val)) {
					that.addErrorMsg($this, '邮箱格式不正确');
				} else {
					/* ajax判断用户名是否存在 */
					$.ajax({
								type : "post",
								url : "/user/email?random="
										+ Math.random(),
								// url:
								// "text.txt?random="+Math.random(),
								data : {
									userEmail : val
								},
								async : false,
								// dataType: "json",
								success : function(data) {
									if (data == false) {
										that.addErrorMsg($this,'该邮箱已被注册');
									} else {
										that.clearErrorMsg($this);
									}
								}
							});
				}
			}else if (typename == 'psd') {
                var $cfm_psd = $('#cfm_psd'),
                    cfm_psd_val = $.trim($cfm_psd.val());
                if (val.length<8 || val.length >16) {
                    that.addErrorMsg($this,'长度必须在8-16之间');
                }else{
                	/* 密码必须为数字 字母 字符的集合 */
//                    var regn = /\d/gi,
//                    	regl = /[a-zA-Z]/gi,
//                    	regz = /[`\-=~!@#$%^&*()_+\[\]\\;',.\/\\{}\|:"<>\?]/gi;
//                    if(!regn.test(val) || !regl.test(val) || !regz.test(val)){
//                    	that.addErrorMsg($this,'密码由数字、字母、字符组成');
//                    };
                };
                
                if (cfm_psd_val != '' || cfm_psd_val.length != 0) {
                    if (val != cfm_psd_val) {
                        that.addErrorMsg($cfm_psd,'两次输入密码不一致');
                    }else{
                        that.clearErrorMsg($cfm_psd);
                    };
                };
            }else if (typename == 'cfm_psd') {
                var psd = $.trim($('#psd').val());
                if (val != psd) {
                    that.addErrorMsg($this,'两次输入密码不一致');
                };
            }else if (typename == 'vftn_code') {
                
            }else if (typename == 'picode') {
                
            };
        });
        /*判断手机号，是否可以发送短信验证码*/
        that.$inputs.filter("[name='phone']").on('keyup', function(event) {
            var $send = $('#getvftn_code'),
            	$this = $(this),
                val = $.trim($this.val());
            //if(BSTYUN.register._timer != null){return false;};
            if (!BSTYUN.check.isMobile(val)) {
                $send.addClass('disabled');
            }else{
            	/*存在倒计时，清空倒计时*/
                if(that._timer != null){
                	$("#getvftn_code").removeClass('disabled').text('免费获取验证码');
                	clearInterval(that._timer);
                }
                $send.removeClass('disabled');
                /*判断手机号，是否已经被注册*/
                $.ajax({
                    type: "post",
                    url: "/user/tel?random="+Math.random(),
                    data: {userTel:val},
                    async:false,
                    success: function(data){
                      if(data==false){
                          that.addErrorMsg($this,"该手机已被注册");
                          $send.addClass("disabled");
                      }else{
                    	  that.clearErrorMsg($this);
                    	  $send.removeClass("disabled");
                      }
                   }
                });
            }
        });
        /*判断邮箱，是否可以发送邮件*/
        that.$inputs.filter("[name='email']").on('keyup', function(event) {
//            var $send = $('#getvftn_code'),
            	$this = $(this),
                val = $.trim($this.val());
            //if(BSTYUN.register._timer != null){return false;};
            if (!BSTYUN.check.isEmail(val)) {
//                $send.addClass('disabled');
            }else{
//                $send.removeClass('disabled');
                /*判断邮箱，是否已经被注册*/
				$.ajax({
							type : "post",
							url : "/user/email?random="
									+ Math.random(),
							// url:
							// "text.txt?random="+Math.random(),
							data : {
								userEmail : val
							},
							async : false,
							// dataType: "json",
							success : function(data) {
								if (data == false) {
									that.addErrorMsg($this,'该邮箱已被注册');
//									 $send.addClass("disabled");
								} else {
									that.clearErrorMsg($this);
//									$send.removeClass("disabled");
								}
							}
						});
            }
        });
    },
    sendSmsCode: function(argument) {
        var that = this,
            $send = $('#getvftn_code'),
            $phone = that.$inputs.eq(3),
            val = null;
            $send.on('click', function(event) {
                var $this = $(this);
                if (!$this.hasClass('disabled')) {
                    $this.addClass('disabled');
                    val = $.trim($phone.val());
                    /*发送ajax请求短信验证码*/
                    $.ajax({
                        type: "post",
                        url: "/user/getMsgCode?random="+Math.random(),
                        //url: "text.txt?random="+Math.random(),
                        data: {tel:val},
                        success: function(data){
                            var message = data.message;
                            if(message=="发送失败"){
                                that.addErrorMsg($phone,'短信发送失败，请重试！');
                                $this.removeClass('disabled').text('免费获取验证码');
                                return false;
                            }else if(message=="每天最多只能发送三次"){
                                that.addErrorMsg($phone,'每天最多发三次');
                                $this.removeClass('disabled').text('免费获取验证码');
                                return false;
                            }else{
                                that.addTipMsg($phone,'短信发送成功');
                                /*倒计时重发*/
                                var i = 60;
                                clearInterval(that._timer);
                                that._timer = setInterval(function() {
                                    if (i == 0) {
                                        clearInterval(that._timer);
                                        that._timer = null;
                                        $this.removeClass('disabled').val('免费获取验证码');
                                    } else {
                                        i--;
                                        $this.val('发送验证码(' + i + ')');
                                    }
                                }, 1000);
                            }
                        }
                    });
                }else{
                   /*禁止状态，不能点击*/
                   return false;
                };
            });
    },
	changePicCode : function() {
		var $change = $("#changeImgCode"), $img = $change.prev();
		$change.on('click', function(event) {
			$img.attr('src', '/image/code?random=' + Math.random());
		});
	},
    submitRegister:function() {
        var that = this,
            $submit = $("#go2register");
        $submit.on('click', function(event) {
        	var condition = null;
            var flag = that.flag,
                data = {};
            var checkedWay = $('input:radio[name="RadioGroup1"]:checked').val()
            $.each(that.$inputs, function(index, val) {
                 $(this).trigger('blur');
            });
            if(checkedWay=='phoneReg'){
            	condition = flag.realName != false && flag.phone != false && flag.psd != false && flag.cfm_psd != false && flag.vftn_code != false;
            }else{
            	condition = flag.email != false /*&& flag.psd != false
				&& flag.cfm_psd != false && flag.picode != false;*/
            }
            if (condition) {
            	data.realName = $.trim(that.$inputs.eq(2).val());
            	data.phone = $.trim(that.$inputs.eq(3).val());
            	data.vftn_code = $.trim(that.$inputs.eq(6).val());
                data.psd = $.trim(that.$inputs.eq(7).val());
                data.cfm_psd = $.trim(that.$inputs.eq(8).val());
                data.email = $.trim(that.$inputs.eq(5).val());
//				data.emailCode = $.trim(that.$inputs.eq(1).val()), 
//				data.picode = $.trim(that.$inputs.eq(4).val());
                $.ajax({
                    type: "POST",
                    url : "/user?random="+Math.random(),
                    data: data,
                    async: false,
                    error: function(request) {
                    	BSTYUN.dialog.ok('服务器繁忙，请稍后尝试')
                        return false;
                    },
                    success: function(data) {
                        var messageCode = data.messageCode;
                        var imgSuccess = data.imgSuccess;
                        var saveSuccess = data.saveSuccess;
                        var email = data.email;
                        var sendSuccess = data.sendSuccess;
                        if(messageCode==true){
                            if(imgSuccess==false&&saveSuccess==""){
                                that.addErrorMsg(that.$inputs.filter("[name='picode']"),'验证码错误');
                                return false;
                            }else{
                            	if(checkedWay=='phoneReg'){
                            		if (saveSuccess == true) {
                                        window.location.href = "/user/userCenter/index"
                                    }else {
                                    	BSTYUN.dialog.warn("手机注册失败，请重新操作！");
                                    }
                                }else{
                                	if(sendSuccess==true){
                                		BSTYUN.dialog.confirm('您的注册邮箱：<span style="color:#0baee4">'+email+'</span><br/>'
                                							  +'<span style="margin-left:2.7em;">我们已将注册激活邮件发送到该邮箱，'
                                							  +'请收到邮件后按照提示内容进行激活，完成注册。</span><span style="color:#0baee4">是否立即激活</span>',function(){
                                			var emailIndex = email.indexOf("@");
                                			var mail = email.substring(emailIndex+1); 
                                			window.open("http://mail."+mail,
                                					'_blank',
                                					'width='
                                							+ (window.screen.availWidth - 10)
                                							+ ',height='
                                							+ (window.screen.availHeight - 30)
                                							+ ',top=0,left=0,toolbar=yes,menubar=yes,scrollbars=yes, resizable=yes,location=yes, status=yes,channelmode=yes');
                                    	});
                                	}else{
                                		BSTYUN.dialog.warn("邮箱绑定失败，请重新绑定");
                                	}
                                	
                                }
                                
                            }
                        }else{
                            that.addErrorMsg(that.$inputs.filter("[name='vftn_code']"),'验证码错误');
                            return false;
                        }
                    }
                });
            };
            return false;
        });
    },
    changePicCode:function() {
        var $change = $("#changeImgCode"),
            $img = $change.prev();
        $change.on('click', function(event) {
            $img.attr('src','/image/code?random='+Math.random());
        });
    },
    /*清空$this的错误提示信息*/
    clearErrorMsg:function($this) {
        var $this = $this,
            that = this,
            typename = $this.attr('name');
        
        if(typename == 'realName') {
        	 that.flag.realName = true;
             $this.parent().children('.error_msg').remove();
        }
        if (typename == 'phone') {
            that.flag.phone = true;
            $this.next().children('.error_msg').remove();
        }if (typename == 'email') {
			that.flag.email = true;
			$this.next('.error_msg').remove();
		}else if (typename == 'psd') {
            that.flag.psd = true;
            $this.parent().children('.error_msg').remove();
        }else if (typename == 'cfm_psd') {
            that.flag.cfm_psd = true;
            $this.parent().children('.error_msg').remove();
        }else if (typename == 'vftn_code') {
            that.flag.vftn_code = true;
            $this.next().next().remove();
        }else if (typename == 'picode') {
            that.flag.picode = true;
            $this.parent().next().html('&nbsp;');
        };
    },
    /*显示错误信息*/
    addErrorMsg:function ($this,msg) {
        var $this = $this,
            that = this,
            typename = $this.attr('name');
        if(typename == 'realName') {
        	that.flag.realName = false;
            if($this.next('.error_msg').size() != 0){
            	$this.next('.error_msg').html(msg);
            }else{
            	$this.after('<span class="error_msg">'+msg+'</span>');
            }
        }else if (typename == 'phone') {
            that.flag.phone = false;
            if($this.next().children('.error_msg').size() != 0){
            	$this.next().children('.error_msg').html(msg);
            }else{
            	$this.next().find('input').after('<span class="error_msg">'+msg+'</span>');
            }
//            $this.next().find('input').after('<span class="error_msg">'+msg+'</span>');
        }else if (typename == 'email') {
			that.flag.email = false;
			if($this.next('.error_msg').size() != 0){
            	$this.next('.error_msg').html(msg);
            }else{
            	$this.after('<span class="error_msg">'+msg+'</span>');
            }
//			$this.parent().next().html('<span class="error_msg">' + msg + '</span>');
		}else if (typename == 'psd') {
            that.flag.psd = false;
            if($this.next('.error_msg').size() != 0){
            	$this.next('.error_msg').html(msg);
            }else{
            	$this.after('<span class="error_msg">'+msg+'</span>');
            }
//            $this.after('<span class="error_msg">'+msg+'</span>');
        }else if (typename == 'cfm_psd') {
            that.flag.cfm_psd = false;
            if($this.next('.error_msg').size() != 0){
            	$this.next('.error_msg').html(msg);
            }else{
            	$this.after('<span class="error_msg">'+msg+'</span>');
            }
        }else if (typename == 'vftn_code') {
            that.flag.vftn_code = false;
            if($this.next().next('.error_msg').size() != 0){
                $this.next().next('.error_msg').html(msg);
            }else{
                $this.next().after('<span class="error_msg">'+msg+'</span>');
            }
        }else if (typename == 'picode') {
            that.flag.picode = false;
            $this.parent().next().html('<span class="error_msg">'+msg+'</span>');
        };
    },
    /*显示提示信息*/
    addTipMsg:function ($this,msg) {
        var $this = $this,
            that = this,
            typename = $this.attr('name'),
            $next = $this.next().find('input');
        if (typename == 'phone') {
            that.flag.email = false;
            $next.after('<span class="tip_msg">'+msg+'</span>');
            $next.parent().children('.tip_msg').delay(20000).fadeOut(2000, function() {
               $(this).remove();
            });
        }else if (typename == 'email') {
			that.flag.email = false;
			$next.html('<span class="tip_msg">' + msg + '</span>');
			$next.children('.tip_msg').delay(2000).fadeOut(2000, function() {
				$(this).remove();
			});
		}
    },
    registerByWay: function(){
    	var checkedWay = $('input:radio[name="RadioGroup1"]:checked').val();
    	if(checkedWay=='phoneReg'){
    		$("#prompt").show();
    		$("#go2register").val("同意协议并注册");
    		$(".phone").show();
    		$(".email").hide();
    	}else{
    		$("#prompt").hide();
    		$("#go2register").val("立即绑定邮箱");
    		$(".phone").hide();
    		$(".email").show();
    	}
    }
}

/**
 * 打开百顺通云服务协议
 */
function openDeal(){
//	window.open ('/user/openBstDeal','','height=500,width=800,top=100,left=200,toolbar=no,menubar=no,scrollbars=no, resizable=no,location=no, status=no') 
	var openUrl = "/user/openBstDeal";//弹出窗口的url
//	var iTop = (window.screen.availHeight-30-iHeight)/2; //获得窗口的垂直位置;
//	var iLeft = (window.screen.availWidth-10-iWidth)/2; //获得窗口的水平位置;
	window.open (openUrl,'_blank','width='+(window.screen.availWidth-10)+',height='+(window.screen.availHeight-30)+ 
	',top=0,left=0,toolbar=yes,menubar=yes,scrollbars=yes, resizable=yes,location=yes, status=yes,channelmode=yes');
//	 window.open(openUrl,"new","toolbar=yes,menubar=yes,scrollbars=yes, resizable=yes,location=yes, status=yes)"); 
}
